package com.manager.common.token;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Order(1)
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(TokenManager.getInstance().getTokenName());
        if(StringUtils.isEmpty(token)){
            return true;
        }
        TokenUtils.set(token);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String tokenName = TokenManager.getInstance().getTokenName();
        String token = request.getHeader(tokenName);
        response.setHeader(tokenName,token);
        TokenUtils.remove();
    }
}
